package com.dragon.object;

import java.util.Objects;

/**
 * Object中hashCode方法演示案例
 *
 * @author dragon
 * @since 2019/11/15
 */
public class HashCodeTest {
    private String  name;
    private Integer age;

    public HashCodeTest(String name, Integer age) {
        this.name = name;
        this.age  = age;
    }

    /**
     * 重写equals方法
     *
     * @param o 比较对象
     * @return 是否相同
     */
    @Override
    public boolean equals(Object o) {

        // 对于任何不为null的对象,如果x.equals(null)应该返回false
        if (o == null) {
            return false;
        }

        if (!(o instanceof HashCodeTest)) {
            return false;
        }

        // 两个对象引用了同一个对象
        if (this == o) {
            return true;
        }

        HashCodeTest that = (HashCodeTest) o;

        return Objects.equals(name, that.name) && Objects.equals(age, that.age);
    }

    /**
     * 重写hashCode方法
     *
     * @return
     */
    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    public static void main(String[] args) {
        HashCodeTest hashCodeTest = new HashCodeTest("dragon", 12);
        int          count        = 10;

        for (int i = 0; i < count; i++) {
            System.out.println(hashCodeTest.hashCode());
        }
    }
}


//~ Formatted by Jindent --- http://www.jindent.com
